from django.http import JsonResponse
from django.shortcuts import render
from django.utils.baseconv import base64
from django.utils.decorators import method_decorator
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from common.custom_exceptions import decorator_exception
from common.models import MusicInfo
from common.views import BaseListView, AuthTemplateView, get_obj, AuthShopAPIView, AuthMobileTemplateView
from kill.models import KillProduct, KillRecord
from kill.serializers import KillProductSerializer


class KillProductListView(BaseListView):
    """活动列表"""
    template_name = 'kill/list.html'
    model = KillProduct
    context_object_name = "kill_list"

    def get_queryset(self):
        self.keyword = self.request.GET.get('keyword', '')
        if self.keyword:
            self.keyword = self.keyword.replace('-', '+').replace('_', '/')
            self.keyword = (base64.decodestring(self.keyword)).strip()
        return KillProduct.objects.filter(title__contains=self.keyword, shop=self.shop, status=KillProduct.STATUS_VALID)

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(KillProductListView, self).get_context_data(**kwargs)


class KillProductAddView(AuthTemplateView):
    """新建活动"""
    template_name = 'kill/add.html'
    serializer_class = KillProductSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['musics'] = MusicInfo.objects.filter(status=MusicInfo.STATUS_VALID)

        return super(KillProductAddView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        serializer = KillProductSerializer(data=request.POST)
        if serializer.is_valid():
            serializer.save(shop_id=kwargs['shop_id'], status=KillProduct.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': '活动添加失败！', 'errors': serializer.errors})


class KillProductEditView(AuthTemplateView):
    """新建活动"""
    template_name = 'kill/edit.html'
    serializer_class = KillProductSerializer

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        kwargs['kill'] = get_obj(KillProduct, id=self.request.GET.get('id'))
        kwargs['musics'] = MusicInfo.objects.filter(status=MusicInfo.STATUS_VALID)

        return super(KillProductEditView, self).get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        kill = get_obj(KillProduct, id=request.POST.get('id'))
        serializer = KillProductSerializer(kill, data=request.POST)
        if serializer.is_valid():
            serializer.save(status=KillProduct.STATUS_VALID)
            return JsonResponse({'status': 0, 'detail': 'success'})
        else:
            return JsonResponse({'status': 1, 'detail': serializer.errors, 'errors': serializer.errors})


class KillProductShelveView(AuthShopAPIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        if not {'title', 'id'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        kill = get_obj(KillProduct, id=request.data.get('id'), status=KillProduct.STATUS_VALID)
        if not kill:
            return Response({'status': 1, 'detail': '活动不存在！'})
        kill.shelve = not kill.shelve
        kill.save()
        return Response({'status': 0, 'detail': 'success'})


class KillProductDeleteView(AuthShopAPIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        """
        活动删除API
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        if not {'items'}.issubset(request.data):
            return Response({'status': 1, 'detail': '参数错误'})
        id_list = request.data.get("items").split(',')
        kill_list = KillProduct.objects.filter(status=KillProduct.STATUS_VALID, id__in=id_list)
        if not kill_list:
            return Response({'status': 1, 'detail': '活动列表不存在！'})
        for kill in kill_list:
            kill.status = KillProduct.STATUS_INVALID
            kill.save()
        return Response({'status': 0, 'detail': 'success'})


class KillProductOrderListView(BaseListView):
    """活动列表"""
    template_name = 'kill/order_list.html'
    model = KillProduct
    context_object_name = "order_list"

    def get_queryset(self):
        self.keyword = self.request.GET.get('keyword', '')
        # 测试错误邮件
        # raise Exception('测似错误邮件')
        if self.keyword:
            self.keyword = self.keyword.replace('-', '+').replace('_', '/')
            self.keyword = (base64.decodestring(self.keyword)).strip()
        return KillRecord.objects.filter(name__contains=self.keyword, info__shop=self.shop,
                                           status=KillRecord.STATUS_VALID)

    def get_context_data(self, **kwargs):
        kwargs['secure'] = self.request.is_secure()
        return super(KillProductOrderListView, self).get_context_data(**kwargs)


class KillProductMobileListView(AuthMobileTemplateView):
    template_name = 'kill/mobile_list.html'

    def get_context_data(self, **kwargs):
        kwargs['kill_list'] = KillProduct.objects.filter(status=KillProduct.STATUS_VALID, shelve=True, shop=self.shop)
        return super(KillProductMobileListView, self).get_context_data(**kwargs)


class KillProductDetailView(AuthMobileTemplateView):
    template_name = 'kill/detail_view.html'

    def get_context_data(self, **kwargs):
        kwargs['kill'] = self.kill
        kwargs['has_join'] = KillRecord.objects.filter(
            info=self.kill,
            status=KillRecord.STATUS_VALID,
            user=self.request.user
        ).exists()
        return super(KillProductDetailView, self).get_context_data(**kwargs)

    def get(self, request, *args, **kwargs):
        self.kill = get_obj(KillProduct, id=kwargs['product_id'], status=KillProduct.STATUS_VALID)
        if not self.kill:
            return render(request, 'mobile/message.html', {'message': '活动不存在，请退出重试！'})
        if not self.kill.shelve:
            return render(request, 'mobile/message.html', {'message': '活动未上架！'})
        return super(KillProductDetailView, self).get(self, request, *args, **kwargs)

    @method_decorator(decorator_exception)
    def post(self, request, *args, **kwargs):
        return JsonResponse({'status': 0, 'detail': ''})
